package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    @Override
    public ResponseResult<List<WmChannel>> listByName(ChannelDto dto) {

        IPage<WmChannel> page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();

        if (!StringUtils.isEmpty(dto.getName())) {

            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        IPage<WmChannel> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel entity) {

        if (entity.getName() == null || StringUtils.isEmpty(entity)) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(WmChannel::getName, entity.getName());

        WmChannel one = this.getOne(queryWrapper);

        if (one != null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        entity.setCreatedTime(new Date());

        this.save(entity);

        return ResponseResult.okResult(entity.getId());
    }
}
